package org.cypress.rtpack.common.executor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by vv on 2016/9/1.
 */
public class ThreadExecutors {

	private static final Logger LOGGER = LoggerFactory.getLogger(ThreadExecutors.class);

	private static ThreadPoolExecutor bizPool = newCachedThreadPool(10, 10, "normalize");

	/**
	 * 对于提交新任务，必须等到有线程池中的线程接收，才解除阻塞
	 *
	 * @param maxPoolSize 最大线程数
	 * @param poolName 线程池名字
	 * @return 线程池
	 */
	public static ThreadPoolExecutor newCachedThreadPool(int cortPoolSize, int maxPoolSize, String poolName) {

		return new ThreadPoolExecutor(cortPoolSize, maxPoolSize, 60L, TimeUnit.SECONDS,
				new SynchronousQueue<Runnable>(), new NamedThreadFactory(poolName), new RecyclePolicy());
	}

	public static class RecyclePolicy implements RejectedExecutionHandler {

		public RecyclePolicy() {
		}

		public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
			if (!executor.isShutdown()) {
				try {
					// 主线程发现队列满，休息500毫秒，然后重新尝试
					TimeUnit.MILLISECONDS.sleep(500);
				} catch (InterruptedException e) {
					LOGGER.error("Interrupt exception in recycle policy.", e);
				}
				executor.submit(r);
			}
		}
	}

	public static ThreadPoolExecutor getBizPool() {
		return bizPool;
	}
	
}
